<!--
@Description:跳转定制产品(方案)的范围配置
@fileName CustomizationRangeConfig.vue
@Author:zqy
@Date:2024-11-18 15:23:20
@Last Modified by:zqy
@Last Modified time:2024-11-18 15:23:20
-->
<template>
  <el-dialog
    ref="refDlg"
    v-el-drag-dialog
    width="650px"
    title="定制产品配置"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @close="closeDialog"
  >
    <div class="table-main">
      <el-form ref="refForm" :model="formData" :rules="formRules" size="mini" label-width="90px">
        <el-form-item label="方案类型：" prop="typeCodes">
          <QupDictCheckbox
            v-model="formData.typeCodes"
            dict-type-code="DESIGN_TYPE"
            domain-code="marketing"
            app-code="fazx"
            @data-change="getDesignTypeList"
          />
        </el-form-item>
        <el-form-item label="品类：" prop="categoryList">
          <div style="margin-botton:10px"><el-button type="primary" size="mini" @click="handleAddRow">新增</el-button></div>
          <div class="table-list-box">
            <el-table :data="formData.categoryList" border header-row-class-name="table-list-header" style="width:100%">
              <el-table-column label="序号" type="index" width="50" align="center" />
              <el-table-column prop="suite" label="空间" min-width="150">
                <template slot-scope="scope">
                  <qup-search-select-picker
                    placeholder="请选择"
                    :url="spaceUrl"
                    value-name="spaceCode"
                    lable-name="spaceName"
                    value-key="id"
                    method="get"
                    :params="{query:{},type:1}"
                    :value.sync="scope.row.spaceCode"
                    :lable.sync="scope.row.spaceName"
                    :current-id.sync="scope.row.spaceId"
                    @change="clearFormData(scope.row,'spaceId')"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="suite" label="品类" min-width="150">
                <template slot-scope="scope">
                  <qup-search-select-picker
                    placeholder="请选择"
                    :url="categroyUrl"
                    value-name="id"
                    lable-name="categoryName"
                    value-key="id"
                    method="get"
                    :params="{query:{ spaceCode:scope.row.spaceCode},type:1}"
                    :value.sync="scope.row.categoryId"
                    :lable.sync="scope.row.categoryName"
                    :current-id.sync="scope.row.spaceId"
                    :parent-id="scope.row.spaceCode"
                    must-pid
                  />
                </template>
              </el-table-column>

              <el-table-column label="操作" width="80" align="center">
                <template v-slot="{row,$index}">
                  <el-button type="text" size="mini" class="cus-mini-btn" @click="handleDelete(row,$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>

    </div>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="closeDialog">取 消</el-button>
      <el-button type="primary" size="mini" @click="handleSure">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'CustomizationRangeConfig',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    selectedId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      spaceUrl: `${process.env.VUE_APP_BASE_API}/api/v1/scheme/2.0/getAllOneSpace`,
      categroyUrl: `${process.env.VUE_APP_BASE_API}/api/v1/scheme/2.0/getCategoryByOneSpace`,
      designDictData: [],
      formData: {
        typeCodes: [],
        categoryList: [
          {
            spaceId: '',
            spaceName: '',
            spaceCode: '',
            categoryId: '',
            categoryName: ''
          }
        ]
      },
      formRules: {
        typeCodes: [
          { required: true, message: '必选', trigger: 'change' }
        ],
        categoryList: [
          { required: true, message: '必须添加一个品类', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    selectedId(val, oldVal) {
      this.initData(val)
    }
  },
  created() {
    this.initData(this.selectedId)
  },
  methods: {
    closeDialog() {
      for (const key in this.formData) {
        this.$set(this.formData, key, key === 'typeCodes' ? [] : '')
      }
      this.dialogShow = false
    },
    clearFormData(row, field) {
      if (field === 'spaceId') {
        this.$set(row, 'categoryId', '')
        this.$set(row, 'categoryName', '')
      }
    },
    initData(str) {
      if ([undefined, null, ''].includes(str)) {
        return {}
      }
      let params = {}
      try {
        params = JSON.parse(str)
      } catch { params = {} }
      for (const key in this.formData) {
        let value = params[key] || (key === 'categoryList' ? [] : '')
        if (key === 'typeCodes') {
          value = value.split(',')
        }
        this.$set(this.formData, key, value)
      }
    },
    getDesignTypeList(data) {
      this.designDictData = data || []
    },
    handleSure() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          const { typeCodes, categoryList } = this.formData
          if (categoryList.length === 0) {
            this.$message.warnin('品类不能为空，请新增')
            return
          }
          const categoryNames = []
          const flag = categoryList.every(v => {
            categoryNames.push(`${v.spaceName}-${v.categoryName}`)
            return !!v.spaceCode && !!v.categoryId
          })
          if (!flag) {
            this.$message.warning('品类存在待完善的行数据，请检查后再提交')
            return
          }

          const typeName = this.designDictData.filter(v => typeCodes.includes(v.dictCode)).map(v => v.dictName)
          const params = {
            ...this.formData, ...{ typeName, typeCodes: typeCodes.join(',') }
          }
          const name = `${typeName.join(',')}_${categoryNames.join('|')}`
          this.$emit('change', {
            value: JSON.stringify(params),
            name: name
          })
          this.closeDialog()
        }
      })
    },
    handleAddRow() {
      this.formData.categoryList.push({
        spaceId: '',
        spaceName: '',
        spaceCode: '',
        categoryId: '',
        categoryName: ''
      })
    },
    handleDelete(row, index) {
      this.formData.categoryList.splice(index, 1)
    }
  }
}
</script>

<style lang='scss' scoped>
/deep/ .cus-mini-btn{
  padding: 0 5px !important;
}
</style>
